We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Cannot use $url->get() with 'for'. It's error A dependency injector container is required to obtain the "url" service.

I have this uri di in config/services.php

use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\Url as UrlResolver;

$di = new FactoryDefault();

/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->set('url', function () use ($config) {
    $url = new UrlResolver();
    $url->setBaseUri($config->application->baseUri);

    return $url;
});

/**
 * add router support.
 */
$di->set('router', function() {
    include __DIR__.'/router.php';
    return $router;
});

In my router.

$router = new Phalcon\Mvc\Router();

$router->removeExtraSlashes(true);

$router->add(
    '/{lang:[a-z]{2}}/index/test2',
    array(
        'controller' => 2,
        'action' => 3,
    )
)->setName('test2');

In my controller

echo $url->get(
    array(
        'for' => 'test2',
    )
);

Results: A dependency injector container is required to obtain the "url" service

How do i make it work? Is this bug?



43.9k
Accepted
answer

Hi,

try :


echo $this->url->get(
    array(
        'for' => 'test2',
    )
);


43.9k

Services are application wide but they have to be called in the application context:

eg in controllers <=> $this->service (where service = url, db, config ... = the ones that are registred in the di).

Have a nice coding time with phalcon